/**
 * Created by JLB1 on 2017/2/7.
 */

import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Clipboard from 'clipboard';
import AJAX from '../../lib/ajax';
import Tools from '../../lib/tools';
import Dialog from '../MyPackage/components/Dialog';
import InfiniteScroll from '../MyPackage/components/InfiniteScroll';
import { addErrorListener } from '../../lib/handleError';

require('../../styles/common.less');
require('../../styles/lux.less');
require('../../styles/resetWeui.less');
require('./NewPickUpList.less');

let PSIZE = 10;

const loader = <div className="loader">
    <i className="weui-loading"></i>
</div>;

class NewPickUpList extends Component {
    constructor(props) {
        super(props);
        this.state = {
            new_currentPage: 1,
            isLoaded: false,
            error: false,
            stationData: null,  // 驿站信息
            new_unpickList: null,   //  驿站下未取包裹
            new_unpickCount: null,   // 
        };
        this.cur_type = null;
        this.cur_stationId = null;
        this.cur_cabinetId = null;
    }

    componentWillMount() {
        addErrorListener()();

        this.cur_stationId = Tools.getParams().station_id;
        this.cur_cabinetId = Tools.getParams().cabinet_id;
        this.cur_type = Tools.getParams().type;
        this.fetchList({});
    }

    componentDidMount() {
        new Clipboard('.right-btn');
        new Clipboard('.icon-copy');
    }

    fetchList({ page_num = 1, PSIZE = 10 }) {

        if (this.new_unpick_pending) { return; }
        this.new_unpick_pending = true;
        const params = {
            startTime: Tools.getDate(),
            pageIndex: page_num,
            pageSize: PSIZE,
        };
        this.cur_stationId && (params.stationId = this.cur_stationId);
        this.cur_cabinetId && (params.storagePid = this.cur_cabinetId);
        this.cur_type && (params.storageType = this.cur_type);

        //获取详情
        AJAX.request('new_unpick_list', params, data => {
            const {
                list,
                count,
            } = data.body;
            if (page_num === 1) {
                const stationData = {
                    address: list[0].addr,
                    phone: list[0].servicePhone,
                    storageType: list[0].storageType,
                };
                this.setState({ stationData });
            }
            if (data.code === 0) {
                const { new_unpickList } = this.state;
                this.setState({
                    new_currentPage: page_num,
                    new_unpickCount: count,
                    isLoaded: true,
                    new_unpickList: page_num === 1 ? list : [...new_unpickList, ...list],
                });
                this.new_unpick_pending = false;
            }
        });
    }

    jumpNewUnPick(item) {
        const { new_unpickCount } = this.state;
        window.location.href = `./NewPickUpDetail?order_id=${item.orderId}&count=${new_unpickCount}&order_type=${item.storageType}`;
    }

    loadMoreUnPickup() {
        const { new_currentPage, new_unpickCount } = this.state;
        if (new_currentPage * PSIZE < new_unpickCount) {

            this.fetchList({ page_num: new_currentPage + 1 })
        }
    }

    /**
     * 
     * @param {*} id 
     * 新驿站 一键开箱 
     */
    handleNewPickup = (order, e) => {
        e.stopPropagation();
        // 是否需要支付开箱
        const { new_unpickCount } = this.state;
        AJAX.request('getCharge', { orderId: order.orderId }, data => {
            if (data.code === 0 && data.body.amount === 0) {
                Dialog.confirm({
                    title: '',
                    content: '检测到您当前位置与柜体距离较远！请核对您的位置与柜体位置是否一致，否则由此带来的损失由您负责。',
                    okText: '仍要开箱',
                    cancelText: '取消',
                    onOK: () => {
                        window.location.href = `./OpenBoxNewFinal?order_id=${order.orderId}`
                    },
                });
            } else {
                window.location.href = `./NewPickUpDetail?order_id=${order.orderId}&count=${new_unpickCount}&order_type=${order.storageType}`;
            }
        });
    }

    /**
     * 新驿站确认取件
     */
     handleNewSelfPickup = (order, e) => {
        e.stopPropagation();
        const that = this;
        Dialog.confirm({
            title: '提示',
            htmlContent: (<div style={{ padding: '15px' }}>
                <div style={{ color: '#999', marginBottom: '10px' }}>请确认是否已取走</div>
                <div style={{ color: 'red' }}>注意: 确认取走后，该包裹视为本人取走。</div>
            </div>),
            okText: '确认',
            cancelText: '取消',
            onOK: () => {
                // 自助取件
                AJAX.request('new_pickUp', { orderId: order.orderId, stationId: order.stationId }, data => {
                    const wx_type = window.localStorage.getItem('wx_type');
                    window.location.href = `./PickUp?wx_type=${wx_type}`;   //返回首页
                });
            },
        })
    }

    render() {
        const {
            new_unpickList,
            new_unpickCount,
            stationData,
            isLoaded,
            new_currentPage
        } = this.state;

        let has_more = false;
        const loadMore_func = this.loadMoreUnPickup.bind(this)
        //判断是否需要加载更多
        if ((new_currentPage * PSIZE) < new_unpickCount) {
            has_more = true;
        } else {
            has_more = false;
        }

        return (
            <div>
                {isLoaded ? (<div>
                    <div className="header stationInfo">
                        <div>{stationData.address}{stationData.storageType === 4 && '(暂存区)'}</div>
                        <div className="serverPhone">
                            <img className="phoneIcon" src="//wechat.jinlb.cn/assets/images/detail-phone.png" />
                            <div>服务电话: {stationData.phone}</div>
                            <a href={`tel:${stationData.phone}`} ><img className="telIcon" src="//wechat.jinlb.cn/assets/images/phone.png" /></a>
                        </div>
                    </div>
                    <div className="unpick-count">
                        未取包裹: {new_unpickCount}个
                    </div>
                    <div className="expressList">
                        {new_unpickCount > 0 && <InfiniteScroll
                            threshold={15}
                            loadMore={loadMore_func}
                            hasMore={has_more}
                            loader={loader}>
                            {new_unpickList && new_unpickList.length > 0 && new_unpickList.map(item => {
                                return (
                                    <div className="expressCard" key={item.orderId} onClick={() => { this.jumpNewUnPick(item); }} >
                                        <div className="lux-d-f expressInfo">
                                            <img className="expressIcon" src={item.expressLogo} />
                                            <div className="lux-fz16 lux-c333 lux-fw-b wordOmit">{item.expressName} {item.expCode}</div>
                                            <img className="copyIcon" src="//wechat.jinlb.cn/assets/images/detail-copy.png" onClick={(e) => {
                                                e.stopPropagation();
                                                e.nativeEvent.stopImmediatePropagation();
                                                Tools.copyExpCode(item.expCode);
                                            }} />
                                        </div>
                                        <div className="lux-d-f pickupInfo">
                                            <div style={{ flex: 1 }}>
                                                <div className="openCode">
                                                    <div>取件码: {item.openCode}</div>
                                                </div>
                                            </div>
                                            <div>
                                                <img className="arrow-right" src="https://wechat.jinlb.cn/assets/images/icon-right-arrow.png" />
                                            </div>
                                        </div>
                                        <div className="time">
                                            <div>{item.createTime}</div>
                                            {item.storageType === 3 && <div style={{ fontWeight: 500, fontSize: 16 }}>格口号: {item.cellDesc}</div>}
                                        </div>
                                        {/* {item.storageType === 3 && <div className="button-box lux-d-f lux-ai-c">
                                            <div className="lux-flex-1 lux-center">
                                                <div
                                                    className={'right-btn button2'}
                                                    style={{ fontSize: 18, flex: 1, height: 42 }}
                                                    onClick={this.handleNewPickup.bind(this, item)}
                                                >
                                                    一键开箱
                                                </div>
                                            </div>
                                        </div>}
                                        {(item.storageType < 3 && (item.collectPayment === 0 || item.isPaid === 1)) && <div className="button-box lux-d-f lux-ai-c">
                                            <div className="lux-flex-1 lux-center">
                                                <div
                                                    className={'right-btn button2'}
                                                    style={{ fontSize: 18, flex: 1, height: 42 }}
                                                    onClick={this.handleNewSelfPickup.bind(this, item)}
                                                >
                                                    确认取走
                                                </div>
                                            </div>
                                        </div>} */}
                                    </div>
                                )
                            })}
                        </InfiniteScroll>}

                    </div>
                </div>) : loader}
            </div>
        );
    }
}

ReactDOM.render(<NewPickUpList />, document.getElementById('app'));

if (module.hot) {
    module.hot.accept();
}